package com.bangdream.michelia.view.activity.buy;

import android.annotation.SuppressLint;
import android.graphics.Paint;
import android.media.Image;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.PayResult;
import com.bangdream.michelia.entity.PayStatusBean;
import com.bangdream.michelia.entity.courses.BuyCourseBean;
import com.bangdream.michelia.entity.courses.CoursesBean;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.rejava.BaseObserverEntityNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.PublicUtil;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * @date on 2018/8/12 16:15
 * @email 909732184@qq.com
 * 支付信息显示
 */
public class BuyInfo extends SwipeBackActivity {
    private static final int SDK_PAY_FLAG = 0x03;
    private TextView tvPrice, tvOriginalPrice, tvTitle;
    private RelativeLayout btnMenu1, btnMenu2;
    private ImageView iv_menu1, iv_menu2;
    //默认选择支付宝支付  否则微信
    private boolean isZfb = true;

    String courseId,businessId;
    String type;

    @Override
    public int getLayout() {
        return R.layout.activity_buy_info;
    }

    @Override
    public void findId() {
        iv_menu1 = findViewById(R.id.iv_menu1);
        iv_menu2 = findViewById(R.id.iv_menu2);
        btnMenu1 = findViewById(R.id.btnMenu1);
        btnMenu2 = findViewById(R.id.btnMenu2);
        tvTitle = findViewById(R.id.tvTitle);
        tvPrice = findViewById(R.id.tvPrice);
        tvOriginalPrice = findViewById(R.id.tvOriginalPrice);
        tvOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线
        tvOriginalPrice.getPaint().setAntiAlias(true);// 抗锯齿
    }

    @Override
    public void setListener() {
        btnMenu2.setOnClickListener(this);
        btnMenu1.setOnClickListener(this);
    }

    @Override
    public void logic() {
        if (getIntent().getExtras() != null) {
            courseId = getIntent().getStringExtra("id");
            businessId = getIntent().getStringExtra("businessId");
            String price = getIntent().getStringExtra("price");
            String title = getIntent().getStringExtra("title");
            type = getIntent().getStringExtra("type");
            tvTitle.setText(title);
            tvPrice.setText(price);

        }
        initTitleBar(" ", "支付", "", this);
//        setViewData();
    }

    private void setViewData() {
        orderCancle();
//        getPayList();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnMenu1:
                isZfb = true;
                changeSelect();
                break;
            case R.id.btnMenu2:
                isZfb = false;
                changeSelect();
                break;
            case R.id.btnBuy:
                actionBuy();
                break;
            default:
                break;
        }
        super.onClick(view);
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    //调起支付
    private void actionBuy() {
        pd.show();
        if(businessId!=null){
            orderCancle();
//            aliPay(businessId);
        }else{
            getOrderId();

        }


    }

    private void changeSelect() {
        if (isZfb) {
            iv_menu1.setImageResource(R.mipmap.kaoshi_bj_answer_b);
            iv_menu2.setImageResource(R.mipmap.kaoshi_bj_answer_a);
        } else {
            iv_menu2.setImageResource(R.mipmap.kaoshi_bj_answer_b);
            iv_menu1.setImageResource(R.mipmap.kaoshi_bj_answer_a);
        }
    }

    private void getOrderId() {
        Map map = new HashMap();
        map.put("courseId", courseId);
        map.put("price", 0.01);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();

        disposable=RetroFactory.getInstance().buyCourse(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseEntity<BuyCourseBean>>() {
                    @Override
                    public void accept(BaseEntity<BuyCourseBean> bean) throws Exception {
                        if (isZfb) {
                            aliPay(bean.getData().getId());
                        }else{
                            wechatPay();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        ToastUtil.showShortToast(BuyInfo.this, "获取订单号失败");
                    }
                });
    }

    private void aliPay(String id) {
        Map map = new HashMap();
        map.put("businessId", id);
        map.put("money", 0.01);
        map.put("subject", tvTitle.getText().toString() + "");
        map.put("type", type);
        map.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();

        disposable=RetroFactory.getInstance().sendAliPayInfoByApp(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(final ResponseBody body) throws Exception {
                        final String str = body.string();
                        pd.dismiss();
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask(BuyInfo.this);
                                // 调用支付接口，获取支付结果
                                Map<String, String> map = alipay.payV2(str, true);

                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = map;
                                handler.sendMessage(msg);
                            }
                        };
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        String message = throwable.getMessage();
                        ToastUtil.showShortToast(BuyInfo.this, "支付失败" + message);
                        pd.dismiss();
                    }
                });
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    L.e("resultStatus==" + resultStatus);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(BuyInfo.this, "支付成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(BuyInfo.this, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(BuyInfo.this, "支付失败",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                }
            }
        }
    };



    @SuppressLint("CheckResult")
    private void wechatPay(){
        Map map = new HashMap();
        map.put("businessId", courseId);
        map.put("ip", PublicUtil.getLocalIpAddress(this));
        map.put("money", 0.01);
        map.put("subject", tvTitle.getText().toString() + "");
        map.put("type", 3);
        map.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();

        disposable=RetroFactory.getInstance().sendAliPayInfoByApp(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(final ResponseBody body) throws Exception {
                        final String str = body.string();
                        pd.dismiss();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        String message = throwable.getMessage();
                        ToastUtil.showShortToast(BuyInfo.this, "支付失败" + message);
                        pd.dismiss();
                    }
                });

    }


    private void orderCancle() {
        Map map = new HashMap();
        map.put("businessId", businessId);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();

        disposable = RetroFactory.getInstance().orderCancel(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseEntity>() {
                    @Override
                    public void accept(BaseEntity buyCourseBeanBaseEntity) throws Exception {
//                        getOrderId();
                        aliPay(businessId);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        ToastUtil.showShortToast(BuyInfo.this, "订单取消失败");
                    }
                });
    }

    private void getPayList() {
        Map map = new HashMap();
        map.put("businessId", courseId);
        map.put("pageNo", 1);
        map.put("pageSize", 2);
        map.put("payMachine", 2);
        map.put("type", 3);
        map.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());

//        map.put("tradeNo",);
//        map.put("payResult",);
//        map.put("orderId",orderId);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();

        RetroFactory.getInstance().getPayList(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<PayStatusBean>>() {
                    @Override
                    public void accept(List<PayStatusBean> beans) throws Exception {
                        ToastUtil.showShortToast(BuyInfo.this, "");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        ToastUtil.showShortToast(BuyInfo.this, "获取失败");
                    }
                });
    }
}
